#!/usr/bin/python3
# -*- coding: utf-8 -*-

import logging
import os.path
import time


class InfoFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.INFO

class ErrorFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.ERROR


class Logger(object):
    def __init__(self,logger):
        '''
        将日志保存到指定的路径文件中
        指定日志的级别，以及调用文件
        '''

        #创建logger文件
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)

        #创建一个handle，用来写入日志文件，按天进行分割
        now = time.strftime("%Y-%m-%d_")
        LOG_PATH = './logs/'
        if not os.path.exists(LOG_PATH):
            os.mkdir(LOG_PATH)  # 如果不存在这个logs文件夹，就自动创建一个
        info_log_name = LOG_PATH+now+'info.log'
        error_log_name = LOG_PATH+now+'error.log'
        log_name = LOG_PATH+now+'.log'

        # 创建总日志handler
        handler = logging.FileHandler(log_name,encoding="utf-8")
        handler.setLevel(logging.INFO)

        # 创建info handler
        info_handler = logging.FileHandler(info_log_name,encoding="utf-8")
        info_handler.setLevel(logging.INFO)
        info_handler.addFilter(InfoFilter())

        # 创建error handler
        error_handler = logging.FileHandler(error_log_name,encoding="utf-8")
        error_handler.setLevel(logging.ERROR)
        error_handler.addFilter(ErrorFilter())

        #创建一个handle，用来输入日志到控制台
        controlhandle = logging.StreamHandler()
        controlhandle.setLevel(logging.INFO)

        #将输出的hangdle格式进行转换
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        info_handler.setFormatter(formatter)
        error_handler.setFormatter(formatter)
        controlhandle.setFormatter(formatter)

        #给logger添加handle
        self.logger.addHandler(handler)
        self.logger.addHandler(info_handler)
        self.logger.addHandler(error_handler)
        self.logger.addHandler(controlhandle)

    def getlog(self):
        return self.logger
